package com.kch.web.controller.system;

import com.github.pagehelper.PageHelper;
import com.kch.common.annotation.Log;
import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.core.page.TableDataInfo;
import com.kch.common.enums.BusinessType;
import com.kch.common.json.JSON;
import com.kch.common.utils.DateUtils;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.AuditRecord;
import com.kch.system.domain.OtherConfig;
import com.kch.system.domain.SysMember;
import com.kch.system.service.AuditRecordService;
import com.kch.system.service.IOtherConfigService;
import com.kch.system.service.ISysMemberService;
import com.kch.system.vo.AuditRecordVO;
import com.kch.system.vo.MemberPageVO;
import com.kch.system.vo.MemberVO;
import com.kch.web.config.CloumnProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/system/member")
@Api(tags = "会员服务")
public class MemberController extends BaseController {

    private String prefix = "system/member";

    @Autowired
    private IOtherConfigService otherConfigService;
    @Autowired
    private CloumnProperties cloumnProperties;
    @Autowired
    private ISysMemberService sysMemberService;
    @Autowired
    private AuditRecordService auditRecordService;

    @RequiresPermissions("system:member:view")
    @GetMapping()
    public String index(ModelMap mmap) throws Exception {
        OtherConfig otherConfig = otherConfigService.selectByCloCode(cloumnProperties.getMember(), null);
        MemberVO memberVO = new MemberVO();
        if (!ObjectUtils.isEmpty(otherConfig)) {
            memberVO = JSON.unmarshal(otherConfig.getContent(), MemberVO.class);
            memberVO.setId(otherConfig.getId());
        }
        mmap.put("member", memberVO);
        return prefix + "/member";
    }

    @Log(title = "会员服务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated MemberVO memberVO) throws Exception {
        OtherConfig otherConfig = otherConfigService.selectByCloCode(cloumnProperties.getMember(), memberVO.getId());
        if (ObjectUtils.isEmpty(otherConfig)) {
            OtherConfig config = new OtherConfig();
            config.setCreateTime(new Date());
            config.setCreateBy(ShiroUtils.getLoginName());
            config.setCloumnCode(cloumnProperties.getMember());
            config.setContent(JSON.marshal(memberVO));
            otherConfigService.insertOtherConfig(config);
        } else {
            otherConfig.setContent(JSON.marshal(memberVO));
            otherConfig.setUpdateBy(ShiroUtils.getLoginName());
            otherConfig.setUpdateTime(new Date());
            otherConfigService.updateById(otherConfig);
        }
        return toAjax(true);
    }

    @RequiresPermissions("system:member:become")
    @GetMapping("/become")
    public String become(ModelMap mmap) throws Exception {
        OtherConfig otherConfig = otherConfigService.selectByCloCode(cloumnProperties.getMember(), null);
        MemberVO memberVO = new MemberVO();
        if (!ObjectUtils.isEmpty(otherConfig)) {
            memberVO = JSON.unmarshal(otherConfig.getContent(), MemberVO.class);
            memberVO.setId(otherConfig.getId());
        }
        mmap.put("member", memberVO);
        mmap.put("tag", sysMemberService.selectIsMember(ShiroUtils.getUserId().intValue()));
        return prefix + "/become";
    }

    @GetMapping("/check")
    @ResponseBody
    @ApiOperation("查询当前用户是否已经是会员或已申请会员 true:是; false:不是")
    public AjaxResult checkIsMember() {
        int number = sysMemberService.selectIsMember(ShiroUtils.getUserId().intValue());
        return number > 0 ? AjaxResult.success(true) : AjaxResult.success(false);
    }

    @PostMapping("/join")
    @ResponseBody
    @ApiOperation("申请成为会员")
    public AjaxResult join() throws Exception {
        SysMember member = sysMemberService.insertSysMember(ShiroUtils.getUserId().intValue(), ShiroUtils.getLoginName());
        //审核记录
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(member.getId());
        auditRecord.setBusType("3");
        auditRecord.setReviewStatus("0");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion("待审核");
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);
        return AjaxResult.success();
    }

    @GetMapping("/join/audit")
    public String auditJoin() throws Exception {
        return prefix + "/join/member";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(MemberPageVO pageVO) {
        startPage();
        List<MemberPageVO> list = sysMemberService.selectMemberPage(pageVO);
        return getDataTable(list);
    }

    @GetMapping("/audit/{id}")
    public String audit(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        return prefix + "/join/audit";
    }

    @PostMapping("/audit")
    @ResponseBody
    public TableDataInfo auditList(@RequestParam("id") Integer id) throws Exception {
        if (ObjectUtils.isEmpty(id)) {
            List<AuditRecordVO> auditRecords = new ArrayList<>();
            return getDataTable(auditRecords);
        }
        startPage();
        List<AuditRecordVO> auditRecords = auditRecordService.selectByBusId(id, "3");
        return getDataTable(auditRecords);
    }

    @GetMapping("/audit/detail/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        mmap.put("men", sysMemberService.selectMemberVO(id));
        return prefix + "/join/detail";
    }

    @GetMapping("/pass/{id}")
    public String pass(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核通过");
        return prefix + "/join/pass";
    }

    @Log(title = "审核通过", businessType = BusinessType.INSERT)
    @PostMapping("/pass")
    @ResponseBody
    public AjaxResult pass(AuditRecordVO auditRecordVO) {
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("3");
        auditRecord.setReviewStatus("1");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        SysMember sysMember = sysMemberService.selectMemberById(auditRecordVO.getId());
        sysMember.setReviewStatus("1");
        sysMember.setStatus("1");
        sysMemberService.updateById(sysMember);
        return AjaxResult.success();
    }

    @GetMapping("/fail/{id}")
    public String fail(@PathVariable("id") Integer id, ModelMap mmap) throws Exception {
        mmap.put("id", id);
        mmap.put("userName", ShiroUtils.getLoginName());
        mmap.put("date", DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        mmap.put("status", "审核不通过");
        return prefix + "/join/fail";
    }

    @Log(title = "审核不通过", businessType = BusinessType.INSERT)
    @PostMapping("/fail")
    @ResponseBody
    public AjaxResult fail(AuditRecordVO auditRecordVO) {
        AuditRecord auditRecord = new AuditRecord();
        auditRecord.setBusId(auditRecordVO.getId());
        auditRecord.setBusType("1");
        auditRecord.setReviewStatus("2");
        auditRecord.setOperTime(new Date());
        auditRecord.setOperUser(ShiroUtils.getUserId().intValue());
        auditRecord.setOpinion(auditRecordVO.getOpinion());
        auditRecord.setCreateBy(ShiroUtils.getLoginName());
        auditRecord.setCreateTime(new Date());
        auditRecordService.insertAuditRecord(auditRecord);

        SysMember sysMember = sysMemberService.selectMemberById(auditRecordVO.getId());
        sysMember.setReviewStatus("2");
        sysMemberService.updateById(sysMember);
        return AjaxResult.success();
    }

    @GetMapping("/manage")
    public String manage(ModelMap mmap) throws Exception {
        return prefix + "/manage/member";
    }

    @PostMapping("/manage/list")
    @ResponseBody
    public TableDataInfo manageList(MemberPageVO pageVO) {
        pageVO.setReviewStatus("1");
        startPage();
        List<MemberPageVO> list = sysMemberService.selectMemberPage(pageVO);
        return getDataTable(list);
    }

    @GetMapping("/status")
    @ResponseBody
    public AjaxResult status(Integer id) {
        try {
            sysMemberService.updateStatus(id);
            return toAjax(true);
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @ApiOperation("获取会员名单")
    @GetMapping("/getMemberList")
    @ResponseBody
    public TableDataInfo getMemberList(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return getDataTable(sysMemberService.selectMemberList());
    }
}
